package zetcode.games.tetris;

import java.util.Random;
import java.lang.Math;

public class Shape{
	private Tetrominoe pieceShape;
	private int coords[][];
	
	public Shape(){
		coords = new int[4][2];
		setShape(Tetrominoe.NoShape);
	}
	
	public void setShape(Tetrominoe shape){		
		pieceShape = shape;
		coords = shape.getGeometry().clone();
	}
	
	private void setX(int index, int x){coords[index][0] = x;}
	private void setY(int index, int y){coords[index][1] = y;}
	public int x(int index){return coords[index][0];}
	public int y(int index){return coords[index][1];}
	public Tetrominoe getShape(){return pieceShape;}
	
	public void setRandomShape(){
		Random r = new Random();
		int x = Math.abs(r.nextInt()) % 7 + 1;
		Tetrominoe[] values = Tetrominoe.values();
		setShape(values[x]);
	}
	
	public int minX(){
		int m = coords[0][0];
		for(int i = 0; i < 4; i++){
			m = Math.min(m, coords[i][0]);
		}
		return m;
	}
	
	public int minY(){
		int m = coords[0][1];
		for(int i = 0; i < 4; i++){
			m = Math.min(m, coords[i][1]);
		}
		return m;
	}
	
	public Shape rotateLeft(){
		if(pieceShape == Tetrominoe.SquareShape){return this;}
		
		Shape result = new Shape();
		result.pieceShape = pieceShape;
		
		for(int i = 0; i < 4; i++){
			result.setX(i, y(i));
			result.setY(i, -x(i));
		}
		return result;
	}
	
	public Shape rotateRight(){
		if(pieceShape == Tetrominoe.SquareShape){return this;}
		
		Shape result = new Shape();
		result.pieceShape = pieceShape;
		
		for(int i = 0; i < 4; i++){
			result.setX(i, -y(i));
			result.setY(i, x(i));
		}
		return result;
	}
}
